import { useRequest } from 'ahooks';
import { Select, Spin } from 'antd';
import { Content } from 'antd/es/layout/layout';
import { useCallback, useEffect, useState } from 'react';

import { getWalletsList } from '../../../../api/services.ts';

import { useGalleryStyles } from './styles.tsx';
import { TokensGrid } from './TokensGrid.tsx';

const handleFilterSelect = (input: string, option?: { label: string; }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase());

export const TabNFTGallery = () => {
    const { styles } = useGalleryStyles();
    const [wallets, setWallets] = useState<string[]>([]);
    
    const { data, loading } = useRequest(getWalletsList, { cacheKey: 'wallets' });

    const handleChangeWallets = useCallback((value: string) => {
        const filteredWallets = data.filter((wallet: string) => wallet.includes(value));
        setWallets(filteredWallets);
    }, [data]);

    useEffect(() => {
        data && handleChangeWallets('');
    }, [data, handleChangeWallets]);

    return (
        <Content className={styles.wrapper}>
            {loading
                ?    <Spin tip="Загружаем кошельки" size="large">
                Загружаем кошельки...
                </Spin>
                : (
                    <>
                        <Select
                            className={styles.select}
                            showSearch
                            placeholder="Введите кошелек"
                            defaultActiveFirstOption={false}
                            filterOption={handleFilterSelect}
                            allowClear
                            onClear={() => handleChangeWallets('')}
                            onChange={(value) => value ? setWallets([value]) : handleChangeWallets('')}
                            onSearch={handleChangeWallets}
                            options={
                                data.map((wallet: string) => ({ value: wallet, label: wallet }))
                            }
                        />
                        <TokensGrid wallets={wallets}/>
                    </>
                )
            }
        </Content>
    );
};